package com.bit.librarymanagementsystem.advice;

import com.bit.librarymanagementsystem.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    @Autowired
    ObjectMapper objectMapper;//进行

    /**
     *判断是否执行beforeBodyWrite方法
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return false;
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof Result<?>){
            return body; // 如果返回结果本身就是要返回的类型就可以无需再次包装
        }
        if (body instanceof String){
           return objectMapper.writeValueAsString(Result.success(body));//转换为json字符串
           //返回结果为String时spring会进行处理导致方法改变,统一返回的参数就必须为String类型的
        }

        return Result.success(body);//将除了String类型的返回结果统一转换为Result类型

    }
}
